package cn.sdhuijin.vms.aop;

import javax.inject.Inject;

import org.apache.commons.lang3.time.DateFormatUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import cn.sdhuijin.vms.dao.ILeaveDao;
import cn.sdhuijin.vms.dao.IPersonDao;
import cn.sdhuijin.vms.model.ApproveStatus;
import cn.sdhuijin.vms.model.Leave;
import cn.sdhuijin.vms.model.Person;
import cn.sdhuijin.vms.sms.util.SmsUtil;

@Component
@Aspect
public class LeaveAspect {
	final Logger logger = LoggerFactory.getLogger(LeaveAspect.class);
	@Inject
	private ILeaveDao leaveDao;
	@Inject
	private IPersonDao personDao;

	@Pointcut("execution(* cn.sdhuijin.vms.dao.ILeaveDao.save(..))")
	public void addLeave() {
	}

	@Around("addLeave()")
	public Object personSms(ProceedingJoinPoint pjp) throws Throwable {
		Leave leave = (Leave) pjp.getArgs()[0];
		Object object = null;
		Person person = personDao.findOne(leave.getPerson().getId());
		if (leave.getStatus() == ApproveStatus.UNTREATED
				&& leave.getLeaveMessage() != null) {
			// 生成messageId
			Long messageId = this.generateMessageId(person.getMaster().getId());
			leave.setMessageId(messageId);
			object = pjp.proceed(new Object[] { leave });// 执行保存
			String msg1 = person.getName()
					+ "提交了一个外出申请，外出时间："
					+ DateFormatUtils.format(leave.getStartTime(),
							"yy-MM-dd HH:mm:ss")
					+ "，返回时间："
					+ DateFormatUtils.format(leave.getEndTime(),
							"yy-MM-dd HH:mm:ss") + ",事由：" + leave.getReason()
					+ ",回复：0" + messageId + "同意外出，00" + messageId + "不同意外出。";
			logger.debug(msg1);
			SmsUtil.sendMessage(person.getMaster().getPhone(), msg1);
			String msg2 = person.getName() + " 您的申请已提交，正在等待处理。";
			logger.debug(msg2);
			SmsUtil.sendMessage(person.getPhone(), msg2);
		} else if (leave.getStatus() != ApproveStatus.UNTREATED) {
			object = pjp.proceed();// 执行保存
			String status = leave.getStatus() == ApproveStatus.AGREE ? "同意"
					: "拒绝";
			if (leave.getApproveMessage() != null) {
				String msg1 = "您" + status + "了" + person.getName() + "的外出申请。";
				logger.debug(msg1);
				SmsUtil.sendMessage(leave.getApprovePerson().getPhone(), msg1);
			}
			if (leave.getLeaveMessage() != null) {
				String msg2 = "您的外出申请被"
						+ status
						+ "了。您可以在"
						+ DateFormatUtils.format(leave.getStartTime(),
								"yy-MM-dd HH:mm:ss")
						+ "到"
						+ DateFormatUtils.format(leave.getEndTime(),
								"yy-MM-dd HH:mm:ss" + "自由出入。");
				logger.debug(msg2);
				SmsUtil.sendMessage(leave.getPerson().getPhone(), msg2);
			}

		} else {
			object = pjp.proceed();// 执行保存
		}
		return object;
	}

	private Long generateMessageId(Long masterId) {
		Long id = leaveDao.getLastMessageId(masterId);
		if (id == null)
			id = 0L;
		id += 1;
		logger.debug("MessageId={}", id);
		return id;
	}
}
